package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.OutputBill;
import com.tianxin.workbao.workBao.bean.OutputBillDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/7/14.
 */

public class OutPutBillProvide extends BaseDataProvide {
    private Integer mPage;
    private OutputBill mOutputBill;
    private List<OutputBill> mOutputBills;
    private UpdateListViewListener mListener;

    public OutPutBillProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mListener = listener;
    }


    public void getOutPutBillByNumber(String number) {
        try {
            getOutPutBillByNumberFromServer(number);
        } catch (OkHttpException e) {
            if (e.getEcode() == -1) {
                mListener.showMessage(e.getEmsg().toString());
            }
            getOutPutBillByNumberFromDb(number);
            e.printStackTrace();
        }
    }


    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mListener.hideProgress();
                handlerResponse(responseObj);
            }

            @Override
            public void onFailure(Object reasonObj) {
                mListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mListener.showMessage(exception.getEcode() + ":" + exception.getEmsg());
                } else {
                    showRequestErrorMessage(mListener,reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    @Override
    public void refreshUI() {
        if (mOutputBills != null && !mOutputBills.isEmpty()) {
            if (mPage > 1) {
                mListener.onLoadMoreData(mOutputBills);
            } else {
                mListener.onRefreshData(mOutputBills);
            }
        }
    }

    private void handlerResponse(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                updateDbData(jsonObject.getString(Constant.RESPONSE_DATA));
            } else {
                mListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mListener,responseObj.toString());
            Log.d(TAG, "handlerResponse: responseObj:"+responseObj);
            e.printStackTrace();
        }
    }

    /**
     * update db data 更新数据库中的数据
     *
     * @param dataJson
     */
    private void updateDbData(String dataJson) {
        if (dataJson.startsWith("[") && dataJson.endsWith("]")) {
            try {
                mOutputBills =JSON.parseArray(dataJson,OutputBill.class);
                mListener.onRefreshData(mOutputBills);
                update(mOutputBills);
            } catch (Exception e) {
                mListener.showMessage("dataJson convent to outputBills Beans Error:");
                Log.d(TAG, "updateDbData: " + dataJson);
                e.printStackTrace();
            }
        } else {
            try {
                mOutputBill = JSON.parseObject(dataJson,OutputBill.class);
                mListener.onRefreshData(mOutputBill);
                update(mOutputBill);
            } catch (Exception e) {
                mListener.showMessage("dataJson convent to outputBill Beans Error:");
                Log.d(TAG, "updateDbData: " + dataJson);
                e.printStackTrace();
            }
        }
    }

    /**
     * true update db data 真正的更新数据库数据
     *
     * @param obj
     */
    private void update(Object obj) {
        OutputBillDao outputBillDao = mGreenDaoHelper.getDaoSession().getOutputBillDao();
        if (obj instanceof List) {
            List<OutputBill> list = (List<OutputBill>) obj;
            for (int i = 0; i < list.size(); i++) {
                outputBillDao.insertOrReplace(list.get(i));
            }
        } else {
            outputBillDao.insertOrReplace((OutputBill) obj);
        }
    }

    public void getOutPutBillByNumberFromServer(String number) throws OkHttpException {
        if (!NetworkUtils.isConnected(mContext)) {
            throw new OkHttpException(-1, "网络未开启，从本地获取！");
        } else {
            String url = URL.getOutPutBillByNumUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("obnum",number);
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        }
    }

    public void getOutPutBillByNumberFromDb(String number) {
        OutputBillDao outputBillDao = mGreenDaoHelper.getDaoSession().getOutputBillDao();
        Query<OutputBill> query = outputBillDao.queryBuilder().where(OutputBillDao.Properties.Obnum.eq(number))
                .limit(1).build();
        List<OutputBill> outputBills = query.list();
        if (outputBills.size() > 0) {
            mOutputBill = outputBills.get(0);
            mListener.onRefreshData(mOutputBill);
        } else {
            mListener.showMessage(mContext.getResources().getString(R.string.no_data));
        }
    }
}
